﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using cpe.cpein.UI.UserCpeInServiceReference;
using Gs = cpe.cpein.UI.GroupCpeInServiceReference;

namespace cpe.cpein.UI.Controls
{
    /// <summary>
    /// Interaction logic for UCListUsers.xaml
    /// </summary>
    public partial class UCListUsers : UserControl
    {
        #region Variables

        /// <summary>
        /// Groups of the control.
        /// </summary>
        private List<User> _users = new List<User>();
        public List<User> MyUsers
        { 
            get { return _users; } 
            set { _users = value; } 
        }

        
        /// <summary>
        /// Current user.
        /// </summary>
        User _currentUser;

        /// <summary>
        /// Current Main window
        /// </summary>
        FMainWindow _WinParent;

        /// <summary>
        /// Group to fill and add to the DB
        /// </summary>
        UCAddGroup _ucGroupToAdd;

        #endregion

        #region Create and Open

        /// <summary>
        /// Default constructor.
        /// </summary>
        public UCListUsers()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Default constructor.
        /// </summary>
        public UCListUsers(User current, FMainWindow WinParent)
        {
            InitializeComponent();
            this._currentUser = current;
            this._WinParent = WinParent;
        }

        /// <summary>
        /// Function fires when the UC is Loaded.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            this.MyUsers = new List<User>();
            InitializeLists();
        }

        #endregion

        #region Event Methods

        /// <summary>
        /// Function fires when a double=click is fired on the grid.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserGrid_DoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (UserGrid.SelectedValue != null)
            {
                OpenUserDetails(int.Parse(UserGrid.SelectedValue.ToString()));
            }
        }

        /// <summary>
        /// Function fires when Refresh button is clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btRefresh_Click(object sender, RoutedEventArgs e)
        {
            FindUsers();
        }

        #endregion

        #region Methods

        /// <summary>
        /// Function which allows to open the group details
        /// </summary>
        /// <param name="p"></param>
        private void OpenUserDetails(int p)
        {
            using (UsersServiceClient us = new UsersServiceClient())
            {
                User user = us.GetUserByID(p, this._currentUser);
                _WinParent.LoadUserControl(new UCUser(this._currentUser, user));
            }
        }

        /// <summary>
        /// Function which allows to initialize the Lists.
        /// </summary>
        private void InitializeLists()
        {
            Tools.Tools.BeginWaitStatus();
            ThreadPool.QueueUserWorkItem(delegate {
                List<User> usrs = GetUsers(false);
                this.Dispatcher.BeginInvoke(new Action(delegate
                {
                    this.MyUsers.Clear();
                    this.MyUsers.AddRange(usrs);
                    this.UserGrid.ItemsSource = usrs;

                    Tools.Tools.EndWaitStatus();
                }));
            });
        }

        private void FindUsers()
        {
            bool searchInFriends = (this.chkRelation.IsChecked == true);
            Tools.Tools.BeginWaitStatus();
            ThreadPool.QueueUserWorkItem(delegate
            {
                List<User> usrs = GetUsers(searchInFriends);
                this.Dispatcher.BeginInvoke(new Action(delegate
                {
                    this.MyUsers.Clear();
                    this.MyUsers.AddRange(usrs);
                    FilterUsers();
                    this.UserGrid.ItemsSource = MyUsers;

                    Tools.Tools.EndWaitStatus();
                }));
            });
        }

        /// <summary>
        /// Function which allows to filter groups in the grid.
        /// </summary>
        private void FilterUsers()
        {
            if (!String.IsNullOrEmpty(this.txtName.Text))
            {
                var req = from User in MyUsers
                          where User.Name.ToLower().IndexOf(this.txtName.Text.ToLower()) >= 0 || User.Lastname.ToLower().IndexOf(this.txtName.Text.ToLower()) >= 0
                          select User;
                MyUsers = req.ToList();
            }
        }

        /// <summary>
        /// Function used to get the groups.
        /// </summary>
        private List<User> GetUsers(bool searchInFriends)
        {
            using(UsersServiceClient us = new UsersServiceClient())
            {
                List<User> usrs = null;
                if (searchInFriends)
                    usrs = new List<User>(us.GetRelations(this._currentUser, this._currentUser));
                else
                    usrs = new List<User>(us.GetAllUsers(false, this._currentUser));
                return usrs;
            }
        }

        
        /// <summary>
        /// Function which allows to load a UserControl in the form.
        /// </summary>
        /// <param name="uc"></param>
        private void LoadUserControl(UserControl uc)
        {
            _WinParent.ucContent.Content = uc;
        }
        #endregion
    }
}
